"use server";
import prisma from "@/lib/prisma";
import { v4 as uuidv4 } from "uuid";
import { VerificationTokenType } from "@/lib/enums";
export const getVerificationTokenByEmail = async ({
  email,
  type,
}: {
  email: string;
  type: VerificationTokenType;
}) => {
  try {
    const verificationToken = await prisma.verificationToken.findFirst({
      where: { identifier: email, type },
    });
    return verificationToken;
  } catch (error) {
    console.log(error);
    return null;
  }
};

export const getVerificationTokenByToken = async ({
  token,
  type,
}: {
  token: string;
  type: VerificationTokenType;
}) => {
  try {
    const verificationToken = await prisma.verificationToken.findUnique({
      where: { token, type },
    });
    return verificationToken;
  } catch (error) {
    console.log(error);
    return null;
  }
};

export const generateVerificationToken = async ({
  email,
  type,
}: {
  email: string;
  type: VerificationTokenType;
}) => {
  try {
    const token = uuidv4();
    const expires = new Date(new Date().getTime() + 60 * 60 * 1000);

    const existingToken = await getVerificationTokenByEmail({ email, type });
    if (existingToken) {
      await prisma.verificationToken.delete({
        where: {
          id: existingToken.id,
        },
      });
    }
    const verificationToken = await prisma.verificationToken.create({
      data: {
        type: type,
        token: token,
        expires: expires,
        identifier: email,
      },
    });
    return verificationToken;
  } catch (error) {
    console.log(error);
    return null;
  }
};
